import math
import time
import threading
import subprocess
import optparse
import logging as logger
from  datetime import datetime
from common.log_manage import LogManage
from common.utils import set_env
from common.wukong_base import WukongBase

COMMAND_TIMEOUT = 60

class SleepWakeuoTest(WukongBase):

    def __init__(self,devices_sn,hdc_path,log_path,interval,count):
        super(SleepWakeuoTest,self).__init__(devices_sn,hdc_path,log_path)
        self.interval = interval
        self.count = count

    def execute_command(self,command):
        process = None
        try:
            process = subprocess.run(command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=30)
        except subprocess.CalledProcessError as e:
            logger.info("execute_command exception = %s" % e)
        finally:
            if process is not None:
                result = process.stdout.decode().strip()
                return result
            return ""

    def _kill_wukong_process(self):
        data_line = self.execute_command("%s \"ps -ef | grep wukong | grep -v grep \"" % self.hdc_shell)
        pid = self._get_process_pid(data_line)
        cmd_rm = '{} \"kill -9 {}\""'.format(self.hdc_shell,pid)
        self.execute_command(cmd_rm)

    def run(self):
        command = '{} "wukong special -k -i {} -c {}"'.format(self.hdc_shell,self.interval,self.count)
        logger.info("sleep wakeup test command %s" % command)
        process = None
        self._kill_wukong_process()
        self.start_log_thread()
        try:
            process = subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
            while process.poll() is None:
                line = process.stdout.readline().strip()
                logger.info("wukong line = %s " % line.decode())
        except Exception as exception:
            logger.info("run exception = ",exception)

        finally:
            logger.info("sleep wakeup test end")
            self._kill_wukong_process()
            if process is not None:
                process.kill()


    def _get_process_pid(self,data_line):
        if data_line is None or data_line == "":
            return None
        pid_str = " ".join(data_line.split())
        data_array = pid_str.split(" ")
        if len(data_array) < 1:
            return None
        return data_array[1]

    def check_devices(self):
        result = self.execute_command('%s list targets' % self.hdc_path)
        return result.find(self.device_sn) != -1

    def check_execute_status(self,start_time):
        end_time = datetime.now()
        dur_time = (end_time - start_time).seconds
        if dur_time >= self.execute_time :
            logger.info("wukong execute success")
            return
        if not self.check_devices():
            logger.info("%s not find the hdc is not connet or the phone battery is exhausted." % self.device_sn)
            return
        result = self.execute_command('%s "ps -ef | grep wukong | grep -v grep"' % self.hdc_shell)
        logger.info("wukong process info = " + result)
def parse_option():
    parser = optparse.OptionParser()
    parser.add_option("-d","--devices",dest="devices",type="str",default=None,help='hdc list targets')
    parser.add_option("-p", "--hdc path", dest="hdc_path", type="str", default='hdc', help='hdc absolute path')
    parser.add_option("-i", "--interval", dest="interval", type="int", default='3000', help='')
    parser.add_option("-c", "--count", dest="count", type="int", default='1200', help='')
    ret_option,remainder = parser.parse_args()
    if ret_option.devices is None :
        raise ValueError(" please add -d argument (sn)")
    return ret_option
def main():
    option = parse_option()
    log_manage = LogManage(option.devices)
    pc_log_path = log_manage.get_log_dir(log_manage.get_hap_dir_name())
    my_log = log_manage.init_logging(pc_log_path)
    set_env("%s -t %s shell" % (option.hdc_path,option.devices))
    press_test = SleepWakeuoTest(option.devices,option.hdc_path,pc_log_path,option.interval,option.count)
    press_test.run()
    my_log.clear_handlers()

if __name__ == '__main__':
    main()